<template>
	<div>
		<Breadcrumb></Breadcrumb>
		<PageDetailLayout
			@formCancel="mapRuleFormCancel"
			@formSubmit="mapRuleFormSubmit">
			<el-form
				v-loading="mapRuleFormLoading"
				ref="mapRuleFormRef"
				:model="mapRuleForm"
				:rules="mapRuleFormRules"
				size="small"
				label-width="120px">
				<el-form-item label="映射规则类型" prop="mapRuleType" class="width-50">
					<el-select
						v-model="mapRuleForm.mapRuleType" placeholder="请选择映射规则类型"
						class="width-100" @change="mapRuleTypeChange">
						<el-option
							v-for="mapType in mapTypeConfig" :key="mapType.value"
							:label="mapType.label" :value="mapType.value"></el-option>
					</el-select>
				</el-form-item>
				<div v-if="mapRuleForm.mapRuleType === 'control'">
					<ControlMapRule
						ref="ctrlMapFormRef"
						:device-type-data="deviceTypeData"
						:map-rule-form="mapRuleForm"></ControlMapRule>
				</div>
				<div v-if="mapRuleForm.mapRuleType === 'status'">
					<StatusMapRule
						ref="statusMapFormRef"
						:device-type-data="deviceTypeData"
						:map-rule-form="mapRuleForm"></StatusMapRule>
				</div>
				<el-form-item label="备注" class="width-50">
					<el-input type="textarea" v-model="mapRuleForm.remarks" placeholder="请填写备注"></el-input>
				</el-form-item>
			</el-form>
		</PageDetailLayout>
	</div>
</template>

<script>
	import {commonConfig} from "@/config/common";
	import {confirmHandle, deepCopy, messageHandle} from "@/utils";
	import {commonString, msgCode} from "@/config/string";
	import ControlMapRule from './partial/ControlMapRule.vue';
	import StatusMapRule from './partial/StatusMapRule.vue';
	import ParamEnumMapList from './partial/ParamEnumMapList.vue';

	export default {
		name: "PlatformInterfaceUpsert",
		components: {
			ControlMapRule,
			StatusMapRule,
			ParamEnumMapList
		},
		data() {
			return {
				commonConfig: commonConfig,
				mapRuleFormLoading: false,
				platformId: '',
				mapRuleId: '',
				mapTypeConfig: [
					{
						label: '控制下发',
						value: 'control'
					},
					{
						label: '状态上报',
						value: 'status'
					}
				],
				mapRuleForm: {
					mapRuleType: 'control',
					sourceDeviceType: '',
					sourceProp: '',
					paramMapType: commonConfig.commandMapWay[1].value,
					targetDeviceType: '',
					generalCommand: '',
					targetProp: '',
					targetPropInArray: '',
					paramEnumMap: [],
					paramFieldMap: {
						preMin: 0,
						preMax: 100,
						postMin: 0,
						postMax: 100,
					},
					remarks: '',
				},
				mapRuleFormRules: {
					mapRuleType: [{required: true, message: '请选择映射规则类型', trigger: 'change'}],
					sourceDeviceType: [{required: true, message: '请选择原始设备类别', trigger: 'change'}],
					sourceProp: [{required: true, message: '请填写属性名', trigger: 'blur'}],
				},
				deviceTypeData: [],
				genCommandSrcData: [],
				genCommandGroupData: [],
			};
		},
		computed: {
			ctrlParamOptions() {
				const genCommand = this.genCommandSrcData.find(gc => {
					return gc._id === this.mapRuleForm.generalCommand;
				}) || {};
				const {controlParams = []} = genCommand;
				return controlParams;
			},
		},
		watch: {
			'mapRuleForm.targetDeviceType': {
				handler() {
					this.getGenCommandData();
				},
				immediate: true
			}
		},
		activated() {
			this.platformId = this.$route.params.pid;
			this.mapRuleId = this.$route.params.iid;
			this.initMapRuleForm();
			this.getDeviceTypeData();
			this.mapRuleId && this.getMapRuleDetail();
		},
		methods: {
			initMapRuleForm() {
				this.mapRuleForm = {
					mapRuleType: 'control',
					sourceDeviceType: '',
					sourceProp: '',
					paramMapType: commonConfig.commandMapWay[1].value,
					targetDeviceType: '',
					generalCommand: '',
					targetProp: '',
					targetPropInArray: '',
					paramEnumMap: [],
					paramFieldMap: {
						preMin: 0,
						preMax: 100,
						postMin: 0,
						postMax: 100,
					},
					remarks: '',
				}
			},
			getMapRuleDetail() {
				this.mapRuleFormLoading = true;
				const param = {_id: this.mapRuleId};
				API.thirdPartyPlatform.platformInterfaceDetail(param).then(result => {
					this.mapRuleFormLoading = false;
					const {data = {}} = result;
					this.mapRuleForm = data;
				}).catch(err => {
					this.mapRuleFormLoading = false;
				});
			},
			getDeviceTypeData() {
				API.deviceType.deviceTypeAll().then(result => {
					const {data = []} = result;
					this.deviceTypeData = data;
				}).catch(err => {
				});
			},
			getGenCommandData() {
				if (!this.mapRuleForm.targetDeviceType) return;
				const deviceType = this.deviceTypeData.find(dt => {
					return dt._id === this.mapRuleForm.targetDeviceType;
				}) || {};
				const param = {deviceType: deviceType._id};
				API.genCommand.genCommAll(param).then(result => {
					const {data = []} = result;
					this.genCommandSrcData = data;
					this.genCommandGroupData = [];
					// 将通用命令根据命令类型分组
					const initGenCommData = commonConfig.commandType.map(ct => {
						return {...ct, options: []};
					});
					data.forEach(d => {
						const genComm = initGenCommData.find(f => {
							return f.value === d.generalCommandType;
						});
						genComm && (genComm.options.push(d));
					});
					initGenCommData.forEach(gc => {
						const {options = []} = gc;
						options.length && (this.genCommandGroupData.push(gc));
					});
				}).catch(err => {
				});
			},
			mapRuleTypeChange(mapRuleType = '') {
				this.initMapRuleForm();
				this.mapRuleForm.mapRuleType = mapRuleType;
			},
			sourceDeviceTypeChange(deviceType = '') {
				this.mapRuleForm.targetDeviceType = deviceType;
			},
			mapRuleFormCancel() {
				this.$router.go(-1);
			},
			mapRuleFormSubmit() {
				this.$refs['mapRuleFormRef'].validate((valid) => {
					if (!valid) return;
					switch (this.mapRuleForm.mapRuleType) {
					  case 'control':
						  const ctrlMapForm = this.$refs['ctrlMapFormRef'];
						  ctrlMapForm.formValidate().then(valid => {
							  if (!valid) return;
								this.submitHandler();
						  });
					    break;
					  case 'status':
						  const statusMapForm = this.$refs['statusMapFormRef'];
						  statusMapForm.formValidate().then(valid => {
							  if (!valid) return;
							  this.submitHandler();
						  });
					    break;
					  default:
					    break;
					}
				});
			},
			submitHandler() {
				this.mapRuleFormLoading = true;
				const params = {
					platform: this.platformId,
					...this.mapRuleForm
				};
				if (!this.mapRuleId) {
					API.thirdPartyPlatform.platformInterfaceAdd(params).then(result => {
						messageHandle({code: msgCode.ADD_SUCCESS, title: '第三方平台映射规则'});
						this.mapRuleFormLoading = false;
						this.$router.go(-1);
					}).catch(err => {
						this.mapRuleFormLoading = false;
					});
				} else {
					API.thirdPartyPlatform.platformInterfaceEdit(params).then(result => {
						messageHandle({code: msgCode.ADD_SUCCESS, title: '第三方平台映射规则'});
						this.mapRuleFormLoading = false;
						this.$router.go(-1);
					}).catch(err => {
						this.mapRuleFormLoading = false;
					});
				}
			}
		},
	}
</script>

<style scoped lang="less">
	/deep/ .el-tabs {
		box-shadow: none !important;
	}
</style>